import React ,{ useState ,useEffect} from 'react'
import { Button, DatePicker, ConfigProvider, Input, Select, message } from 'antd';
import locale from 'antd/locale/zh_CN';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { RollbackOutlined, SearchOutlined } from '@ant-design/icons';
import 'dayjs/locale/zh-cn';
import TopicProvider from './videoProvide'
import DynamicPagination from '../components/pages/DynamicPagination';
import axios from 'axios';
import '../css/lzk.css'

axios.defaults.baseURL = 'http://localhost:3000/'
dayjs.locale('zh-cn');
const { RangePicker } = DatePicker;

export default function Video() {
  const [selectedValue, setSelectedValue] = useState(undefined);
  const [selectedValues, setSelectedValues] = useState(undefined);
  const [value, setvalue] = useState();
  let [typelist,settypelist]=useState([])
  const [status, setstatus] = useState([]);
  const navigate = useNavigate();
  const [videoList, setvideoList] = useState([]);
  const [totalRecords, settotals] = useState();
  const [page, setpage] = useState(1);
  const [pageSize, setpagesize] = useState(2);
  const [dateRange, setDateRange] = useState([]);

  const columns = [
    {
        align:'center',
        title: '视频名称',
        key: 'content',
        dataIndex: 'content',
        render:(_, record) => (
              <div style={{display:'flex',marginBottom:'0.5rem'}}>
                <img src={record.cover} style={{width:'1rem',height:'1rem',borderRadius:'0.1rem',marginTop:'0.5rem'}} alt="" />
                <div style={{marginTop:'0.7rem'}}>{record.name}</div>
              </div>
        )
    },
    {
        align:'center',
        title: '视频标签',
        dataIndex: 'nid',
        key: 'nid',
        render:(_, record) => (
            <div style={{display:'flex'}}>
                <div style={{background:'#ecedf9',color:'#8f88f5',borderRadius:'0.1rem',padding:'0.1rem'}}>{record.bid[0].name}</div>
                <div style={{background:'#ecedf9',padding:'0.1rem',color:'#8f88f5',borderRadius:'0.1rem',marginLeft:'0.5rem'}}>{record.bid[1].name}</div>
            </div>
        )
    },
    {
        align:'center',
        title: '点赞',
        render:() => (
            <span>2100</span>
        )
    },
    {
        align:'center',
        title: '收藏',
        render:() => (
            <span>200</span>
        )
    },
    {
        align:'center',
        title: '分享',
        render:() => (
            <span>205</span>
        )
    },
    {
        align:'center',
        title: '评论',
        render:() => (
            <span style={{color:'#56d9c9'}}>6</span>
        )
    },
    {
        align:'center',
        title: '更新人',
        render:(_, record) => (
            <span>{record.ren}</span>
        )
    },
    {
        align:'center',
        title: '最后更新时间',
        key: 'end_time',
        dataIndex: 'end_time',
        render:(_, record) => (
            <span>{  dayjs(record.publishTime).format('YYYY-MM-DD HH:mm:ss')}</span>
        )
    },
    {
        align:'center',
        title: '操作',
        render:(_, record) => (
            <span>
                <a onClick={() => handleEdit(record)} style={{ marginLeft: 16 }}>
                    编辑
                </a>
                <a style={{color:'red'}} onClick={() => handleDelete(record._id)} style={{ marginLeft: 16 }}>
                    删除
                </a>
            </span>
        )
    },
];

    const handleDateChange = (dates) => {
        setDateRange(dates);
    };
    const getStatusList=async()=>{
        const {data:{list}} = await axios.get('/kai/getstatu')
        const formattedOptions = list.map(item => ({
            value: item._id,
            label: item.lable
        }));
        setstatus(formattedOptions)
    }

    const handlePageChange = (page, pageSize) => {
      setpage(page)
      setpagesize(pageSize)
    };
    const handleShowSizeChange = (current, size) => {
      setpage(current)
      setpagesize(size)
};
    const sou = ()=>{
        // getactive()
    }
    const getvideoList = async () => {
      try {
        const { data: { list, total } } = await axios.get('/kai/getvideo', {
          params: {
            page,
            pagesize: pageSize,
            zid: selectedValue,
            sid: selectedValues,
            startdate: dateRange[0],
            enddate: dateRange[1],
            keyword: value
          }
        });
        setvideoList(list);
        settotals(total);
      } catch (err) {
        console.error('获取视频列表失败:', err);
      }
    };
    
    const qu = ()=>{
        if (value.length > 0) {
            // 截取字符串，去掉最后一个字符
            setvalue(value.slice(0, -1));  
        }
    }
    const handleChange = (value) => {
      setSelectedValue(value);
};
const handleChanges = (value) => {
      setSelectedValues(value);
};
    useEffect(()=>{
        getvideoList(),
        getStatusList()
    },[page,pageSize,value,dateRange,selectedValue,selectedValues])

  // 编辑视频
  const handleEdit = (record) => {
    navigate(`/zhu/navpage/editvideo/${record._id}`);
  };

  // 删除视频
  const handleDelete = async (id) => {
    try {
      await axios.delete(`/kai/deletevideo/${id}`);
      message.success('删除成功');
      getvideoList();
    } catch (error) {
      message.error('删除失败');
    }
  };

  return (
     <div style={{
      scrollbarWidth:'none',
      overflowY:'auto',
      margin:'auto',
      width: '70%',
      height: '100%',
    }}>
      <div style={{marginTop: '0.6rem',overflow:'hidden',backgroundColor: 'white',width:'100%',height:'30%',borderRadius:'20px'}}>
        <div style={{display:'flex',margin:'0.6rem'}}>
          <div style={{width:'0.16rem',marginTop:'0.1rem',borderRadius:'0.1rem',height:'0.6rem',backgroundColor:'#3dd4a7'}}></div>
          <div style={{fontSize:'0.5rem',marginLeft:'0.2rem'}}>视频列表</div>
        </div>
        <div style={{width:'100%',fontSize:'0.4rem',color:'#999',margin:'1rem 0.6rem'}}>
          <div style={{display:'flex'}}>
            <div>状态</div>
            <div style={{margin:'-0.2rem 0.5rem'}}>
              <Select
                placeholder="请选择"
                defaultValue={selectedValue}
                style={{
                  width: 120,
                  marginTop: '0.1rem',
                }}
                onChange={handleChange}
                options={status}
              />
            </div>
            <div style={{marginLeft:'0.5rem'}}>更新日期</div> 
            <div style={{marginLeft:'1rem',marginTop:'-0.2rem'}}>
              <ConfigProvider locale={locale}>
                <RangePicker onChange={handleDateChange} style={{height:'1rem',width:'10rem'}}/>
              </ConfigProvider>
            </div>
          </div>
          <div style={{display:'flex',marginTop:'1rem'}}>
            <div style={{margin:'-0.2rem 0.1rem'}}>
              <Input 
                onChange={(e)=>{setvalue(e.target.value)}} 
                value={value} 
                style={{height:'1rem',width:'10rem'}} 
                placeholder="请输入关键字" 
              />
            </div>
            <Button 
              onClick={sou} 
              style={{textAlign:'center',lineHeight:'1rem',margin:'-0.2rem 0.3rem',width:'1rem',height:'1rem',background:'#5adbb5',color:'white',borderRadius:'0.1rem'}} 
              type="primary"  
              icon={<SearchOutlined />} 
            />
            <Button 
              onClick={qu} 
              style={{textAlign:'center',lineHeight:'1rem',margin:'-0.2rem 0.3rem',width:'1rem',height:'1rem',color:'black'}} 
              type="primary" 
              color='default' 
              variant="outlined" 
              icon={<RollbackOutlined />} 
            />
          </div>
        </div>
      </div>

      <div style={{marginTop: '0.6rem',overflow:'hidden',backgroundColor: 'white',width:'100%',marginBottom:'1.25rem',borderRadius:'20px'}}>
        <div style={{margin:'0.5rem 25rem',display:'flex'}} >
          <Button 
            onClick={()=>{navigate('/zhu/navpage/Addvideo')}} 
            style={{background:'#5adbb5',color:'white',width:'1.8rem',height:'1rem'}} 
            variant="solid"
          >
            新增
          </Button>
          <Button 
            style={{marginLeft:'0.5rem',width:'2.4rem',height:'1rem'}} 
            color="default" 
            variant="outlined"
          >
            批量操作
          </Button>
        </div>
        <div style={{width:'92%',margin:'0 auto',position:'relative'}}>
          <TopicProvider 
            columns={columns}
            dataSource={videoList}
          />
          <div style={{width:'50%',margin:'0.5rem 17rem'}}>
            <DynamicPagination
              style={{position:'absolute',right:'1rem'}}
              pageSize={pageSize}
              total={totalRecords}
              currentPage={page}
              defaultCurrent={page}
              defaultPageSize={pageSize}
              showQuickJumper
              onPageChange={handlePageChange}
              onShowSizeChange={handleShowSizeChange}
            />
          </div>
        </div>
      </div>
    </div>
  )
}